﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace AxeFrog.Logging
{
	/// <summary>
	/// MasterLogger is thread-safe.
	/// </summary>
	[Export]
	public class MasterLogger
	{
		private readonly ILogger[] _loggers;
		private DateTime _nextStampAfter = DateTime.UtcNow.AddYears(-1);

		[ImportingConstructor]
		public MasterLogger([ImportMany] ILogger[] loggers)
		{
			_loggers = loggers;
		}

		public void Write(object o)
		{
			Write(null, o);
		}

		public void WriteLine(object o)
		{
			Write(null, o + Environment.NewLine);
		}

		public void WriteFormat(string fmt, params object[] vals)
		{
			Write(null, string.Format(fmt, vals));
		}

		public void Write(string category, object o)
		{
			try
			{
				lock(this)
				{
					if(_nextStampAfter <= DateTime.UtcNow)
					{
						_nextStampAfter = DateTime.UtcNow.AddMinutes(15);
						foreach(var logger in _loggers)
							logger.Write(null, "-----------------------------------------" + Environment.NewLine
								+ "Date: " + DateTime.UtcNow + Environment.NewLine
								+ "-----------------------------------------" + Environment.NewLine);
					}
					foreach(var logger in _loggers)
						logger.Write(category, o == null ? "" : o.ToString());
				}
#if DEBUG
				if(Debugger.IsAttached)
					Debug.Write(category == null ? o : category + ": " + o);
#endif
			}
			catch
			{
			}
		}

		public void WriteLine(string category, object o)
		{
			Write(category, o + Environment.NewLine);
		}

		public void WriteFormat(string category, string fmt, params object[] vals)
		{
			Write(category, string.Format(fmt, vals));
		}
	}
}